import { Popconfirm, Skeleton,Modal ,Switch, Tabs, Cascader, Table, Input, Button, Row, Col, Flex, Checkbox, Divider } from 'antd';
import axios from '../../axios';
import { useEffect, useState } from 'react';
import XLSX from 'xlsx';
function Goodsmanger() {
    // 下面是头部
    const [headers, setHeaders] = useState([])
    const getHeader = async () => {
        let res = await axios.get("/store/product/tabs/headers", { params: { temp: new Date().getTime() } })

        let arry = []
        res.map(item => {
            arry.push({
                label: `${item.name}(${item.count})`,
                key: item.type,
            })
        })
        setHeaders(arry)
    }
    const [type, setType] = useState(1)
    const getType = (key) => {
        console.log(key);
        setType(key)
        getList(cateId, keywords, key)
    }
    // 下面是层级联动
    const [options, setOptions] = useState([])
    const getoptions = async () => {
        let res = await axios.get("/category/list/tree", {
            params: {
                status: -1,
                type: 1,
                temp: new Date().getTime()
            }
        })
        setOptions(res)
    }

    const [cateId, setcateId] = useState("")
    const onChange = (arry) => {//把最后一个id作为参数 请求  getList
        setcateId(arry[arry.length - 1])
        getList(arry[arry.length - 1], keywords, type, page)
    };

    //搜索
    const [keywords, setKeywords] = useState("")
    const searchFun = (e) => {
        // console.log(keywords);
        getList(cateId, keywords, type, page)
    }
    // 下面是表格
    const [list, setList] = useState([]);
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const getList = async (cateId = "", keywords = "", type = "1", page = 1) => {
        let { list, total } = await axios.get("/store/product/list", {
            params: {
                page,
                limit: 20,
                cateId,
                keywords,
                type,
                temp: new Date().getTime(),
            }
        })
        setTotal(total)
        setList(list)
    }
    const status=0
    const [columns, setColumns] = useState([
        {
            title: '时间',
            dataIndex: 'addTime',
            key: "addTime",
            hidden: false,
            render: (val) => <b>{val}===</b>

        },
        {
            title: '商品详情',
            dataIndex: 'cateValues',
            key: "cateValues",
            hidden: false,


        },
        {
            title: '价格',
            dataIndex: 'price',
            key: "price",
            hidden: false,


        },
        {
            title: '状态',
            dataIndex: '',
            key: "s",
            hidden: false,
            render:(_,record)=> <Switch  checked={status==1} checkedChildren="开启" unCheckedChildren="关闭" />


        },

        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            render: (_, record) => <Button  onClick={()=>showModal(record)} >详情</Button>,
            hidden: false,
        },
    ]);

    const delFun = (row) => {
        console.log(row.id);
        setList(pre => {
            let index = pre.map(item => item.id == row.id)
            pre.splice(index, 1)
            return [...pre]
        })
        // let index=list.findIndex(item=>item.key==row.id)
        // console.log(index);
    }

    useEffect(() => {
        getHeader()//头部tabs
        getoptions()//二级联动
        getList()//表格
    }, [])

    const onChangePage = (val) => {
        console.log(val);
        setPage(val)
        getList(cateId, keywords, type, val)
    }
    const defaultCheckedList = columns.map((item) => item.key);
    const [checkedList, setCheckedList] = useState(defaultCheckedList);
    const optionss = columns.map(({ key, title }) => ({
        label: title,
        value: key,
    }));
    const newColumns = columns.map((item) => ({
        ...item,
        hidden: !checkedList.includes(item.key),
    }));

    const changeAll = (e) => {
        if (e.target.checked) {
            let arry = [];
            optionss.map(item => arry.push(item.value))
            setCheckedList(arry)
        } else {
            setCheckedList([])
        }
    }
    // 下面是导出



    const exportToExcel = () => {

        const data = [];
        list.map(item => {
            data.push({
                "商品名称": item.storeName,
                "商品价格": "￥" + item.price
            })
        })

        const worksheet = XLSX.utils.json_to_sheet(data);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
        XLSX.writeFile(workbook, "data.xlsx");
    };


    const [isModalOpen, setIsModalOpen] = useState(false);
    const [row,setRow]=useState({})
    const showModal = (row) => {
        
        setRow(row)
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    return (
        <div className='whitebg'>


            {/* <Button type="primary" onClick={showModal}>
                Open Modal
            </Button> */}
            <Modal title="商品详情" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <div>
                     商品详情:{row.storeName}
                </div>
            </Modal>
            <Skeleton />
            <Tabs
                defaultActiveKey="1"
                items={headers}
                onTabClick={(e) => getType(e)}
            />
            <Row>
                <Col span={12}><Cascader
                    fieldNames={{ label: "name", value: "id", children: "child" }}
                    options={options} onChange={onChange} placeholder="选择商品分类" />

                </Col>
                <Col span={12}>{keywords}
                    <Flex>
                        <div>商品搜索</div>
                        <Input placeholder="请输入" value={keywords} onChange={(e) => setKeywords(e.target.value)} />

                        <Button onClick={() => searchFun()}>搜索</Button>
                    </Flex>
                </Col>
            </Row>
            <button onClick={exportToExcel}>导出</button>
            <Checkbox checked={checkedList.length == optionss.length} onChange={changeAll}>全选</Checkbox>
            <Checkbox.Group
                value={checkedList}
                options={optionss}
                onChange={(value) => {
                    setCheckedList(value);
                }}
            />
            <Table
                columns={newColumns}
                expandable={{
                    expandedRowRender: (record) => (
                        <div>
                            <p>商品分类 {record.cateValues}</p>
                            <p>商品价格 {record.price}</p>

                        </div>
                    ),

                    //   rowExpandable: (record) => record.id !== 'Not Expandable',
                }}
                dataSource={list}
                rowKey="id"
                pagination={{
                    defaultCurrent: 1,
                    total,
                    onChange: onChangePage,
                    pageSize: 20,

                    showQuickJumper: true,
                    pageSizeOptions: [20, 40, 60, 80, 100]
                }}
            />


        </div>
    );
}

export default Goodsmanger;